package com.jsoft.pds.bs.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;

import com.jsoft.pds.eis.bo.base.BaseEntity;

/**
 * @author developer 
 */
public abstract class AbstractDaoHibernateImpl {
	
	protected SessionFactory session;
	private static final String FROM = "from";


	public <T> BaseEntity save(BaseEntity baseEntity){
		this.getSession().save(baseEntity);
		return baseEntity;
	}

	public void update(BaseEntity baseEntity){
		this.getSession().update(baseEntity);
	}

	public void delete(BaseEntity baseEntity){
		this.getSession().delete(baseEntity);
	}

	public <T> BaseEntity findWithGet(Class<? extends BaseEntity> clazz, Integer id){
		return (BaseEntity) this.getSession().get(clazz, id);
	}

	public <T> BaseEntity findWithLoad(Class<? extends BaseEntity> clazz, Integer id){
		return (BaseEntity) this.getSession().load(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> findAll(Class<? extends BaseEntity> clazz){
		return this.getSession().createQuery(FROM + " " + clazz.getName()).list();
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> find(BaseEntity baseEntity){
		Criteria criteria = this.getSession().createCriteria(baseEntity.getClass());
		criteria.add(Example.create(baseEntity));
		return criteria.list();
	}

	public Query getQuery(String query){
		return this.getSession().getNamedQuery(query);
	}
	
	public Session getSession(){
		return this.getSessionFactory().getCurrentSession();
	}
	public SessionFactory getSessionFactory() {
		return session;
	}
	public void setSessionFactory(SessionFactory session) {
		this.session = session;
	}
}
